package com.tradeplus.security.dao;

import java.util.List;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import com.tradeplus.security.DESEDE;
import com.tradeplus.security.model.User;

@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class UserDaoImpl implements UserDao {

	private HibernateTemplate hibernateTemplate;

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }
    
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public void saveUser(User user){
		hibernateTemplate.merge(user);
	}


	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public void delete(User user) {
		hibernateTemplate.delete(user);
	}


	@Override
	public User get(int userID) {
		return (User) hibernateTemplate.get(User.class, userID);
	}


	@Override
	public User get(String username) {
		Object[] paramArr = new Object[1];
		paramArr[0] = new String(username);
		return (User)hibernateTemplate.find("from User where username=?", paramArr).get(0);
	}


	@Override
	public User get(String username, String password, String site, String domain) {
		DESEDE desede = new DESEDE(username);
		Object[] paramArr = new Object[2];
		paramArr[0] = new String(username);
		paramArr[1] = desede.encrypt(password);
		
		List<User> users = hibernateTemplate.find("from User where username=? and password=?", paramArr);
		if(users == null || users.size() == 0) {
		    throw new org.springframework.security.authentication.BadCredentialsException(
			    "Invalid username / password combination");
		}
		
		return users.get(0);
	}


	@Override
	public User getUserByEmail(String email) {
		Object[] paramArr = new Object[1];
		paramArr[0] = new String(email);
		return (User)hibernateTemplate.find("from User where email=?", paramArr).get(0);
	}


	@Override
	public List<User> getAllUsers() {
		return hibernateTemplate.find("from User");
	}
}
